<?php
/**
 * Created by PhpStorm.
 * User: lili
 * Date: 2018/12/30
 * Time: 20:58
 */

namespace system\core\model;


use system\core\config\Config;

class Connection
{

    protected static $instance;

    protected $pdo;

    protected $database = [
        // 数据库类型
        'type'            => 'mysql',
        // 数据库连接DSN配置
        'dsn'             => '',
        // 服务器地址
        'hostname'        => '127.0.0.1',
        // 数据库名
        'database'        => '',
        // 数据库用户名
        'username'        => 'root',
        // 数据库密码
        'password'        => '',
        // 数据库连接端口
        'hostport'        => '',
        // 数据库连接参数
        'params'          => [],
        // 数据库编码默认采用utf8
        'charset'         => 'utf8',

    ];



    protected function __construct()
    {


        $this->loadconfig();
//        var_dump($this->database['dsn']);
        try {
            if (!class_exists('PDO')){
                throw new Exception('not found PDO');

            }
            $this->pdo = new \PDO($this->database['dsn'],$this->database['username'],$this->database['password']
                ,array(\PDO::MYSQL_ATTR_INIT_COMMAND => "set names ".$this->database['charset']));
        } catch (\PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }

    }

    public function loadconfig(){
        $database2 = Config::get('database');
        $this->database = array_merge($this->database,$database2);
        $this->database['dsn'] = $this->database['type'].':host='.$this->database['hostname'].';dbname='.$this->database['database'];
    }


    public static function getInstance(){
        if(empty(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        $this->pdo = null;//关闭连接
        
    }


    /**
     * 内部调用方法  用来直接执行SQL语句的方法
     */
    public function query($sql,$data=''){
        $this->statement = $this->pdo->prepare($sql);
        if (false === $this->statement)
            return false;
        if (!empty($data))
        {
            foreach ($data as $k => $v)
            {
                $this->statement->bindValue($k, $v);
            }
        }
        $res = $this->statement->execute();
        if (!$res)
        {
            return false;
//            throw new \Exception('sql:'.$sql.'<====>where:'.json_encode($data).'<====>error:'.json_encode($this->statement->errorInfo()));
        }else{
            $res =  $this->statement->fetchAll(\PDO::FETCH_ASSOC);
            if (empty($res)){
              return   $this->statement->rowCount();
            }else{
                return $res;
            }


        }
    }


    public function lastInsertId(){
         
        return $this->pdo->lastInsertId();
    }

}